﻿using HY.Common;
using HY.Model;
using HY.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;

namespace HY.Web.Controllers
{
    public class SysRoleController : BaseController
    {
        private readonly SysRoleService service;
        public SysRoleController(ILogger<SysRoleController> logger, SysRoleService service) : base(logger)
        {
            this.service = service;
        }

        [Authorize]
        public IActionResult Index()
        {
            return View();
        }
        [Authorize]
        [HttpPost]
        public IActionResult Index(SysRole model)
        {
            Expression<Func<SysRole, bool>> filter = e => true;
            if (!string.IsNullOrEmpty(model.RoleName))
                filter = filter.And(c => c.RoleName.Contains(model.RoleName));
            List<SysRole> list = GlobalClass.GetSysRoleList().Where(filter.Compile()).ToList();
            return Json(Success(list.Count, list));
        }

        public IActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Add(SysRole model)
        {
            DbContext.SysRole.Insert(model);
            CacheHelper.Remove(SystemConst.CacheKey.SysRole);
            return Json(returnModel);
        }

        public IActionResult Edit(int id)
        {
            var model = DbContext.SysRole.GetById(id);
            return View(model);
        }

        [HttpPost]
        public IActionResult Edit(SysRole model)
        {
            service.UpdateRole(model);
            CacheHelper.Remove(SystemConst.CacheKey.SysRole);
            return Json(returnModel);
        }

        [HttpPost]
        public IActionResult Delete(int id)
        {
            DbContext.SysRole.DeleteById(id);
            CacheHelper.Remove(SystemConst.CacheKey.SysRole);
            return Json(returnModel);
        }
    }
}
